<template>
  <fullscreen-container :auto-fullscreen="true" :anti-cheating="true" @cheating-detected="handleCheating" :group-id="groupId">
    <div class="exam-container">
      <!-- 考试头部信息 -->
      <div class="exam-header">
        <div class="exam-title">
          <h2>{{ examInfo.title }}</h2>
          <div class="exam-meta">
            <span>总分: {{ examInfo.totalScore }}分</span>
            <span>及格分: {{ examInfo.passScore || '--' }}分</span>
            <span v-if="examInfo.timeLimit">时长: {{ examInfo.timeLimit }}分钟</span>
          </div>
        </div>
        <div class="exam-timer" v-if="timerVisible">
          <i class="el-icon-time"></i>
          <span class="time-count">{{ formatTime(countdown) }}</span>
        </div>
      </div>

      <!-- 考试内容区域 -->
      <div class="exam-content">
        <el-tabs v-model="activeTab" type="card">
          <el-tab-pane
            v-for="type in questionTypes"
            :key="type.id"
            :label="`${type.name} (${type.count}题, ${type.score}分)`"
            :name="type.id.toString()"
          >
            <div class="question-list">
              <div
                v-for="question in getQuestionsByType(type.id)"
                :key="question.id"
                class="question-item"
                :class="{
                  'answered': isAnswered(question.id),
                  'choice-type': isChoiceType(question.type),
                  'upload-type': getTypeInfo(question.type).hasFile,
                  'text-type': !isChoiceType(question.type) && !getTypeInfo(question.type).hasFile
                }"
              >
                <div class="question-header">
                  <span class="question-index">第{{ question.sort }}题 ({{ question.score }}分)</span>
                  <span class="question-type">{{ question.typeName }}</span>
                </div>
<!--                <div class="question-content" v-html="question.content"></div>-->
                <formula-renderer class="question-content" :html="question.content" />

                <!-- 根据题型动态渲染不同作答区域 -->
                <template v-if="isChoiceType(question.type)">
                  <!-- 选择题选项 -->
                  <div class="question-options">
                    <div
                      v-for="option in question.options"
                      :key="option.id"
                      class="option-item"
                      :class="{
                        'selected': isOptionSelected(question.id, option.id),
                        'multi-selected': isMultiChoiceType(question.type) && isOptionSelected(question.id, option.id)
                      }"
                      @click="handleSelectOption(question.id, option.id)"
                    >
                      <span class="option-code">{{ option.optionCode }}.</span>
<!--                      <span class="option-content" v-html="option.content"></span>-->
                      <formula-renderer class="option-content" :html="option.content" />
                    </div>
                  </div>
                </template>
                <template v-else-if="getTypeInfo(question.type).hasFile">
                  <!-- 文件上传题 -->
                  <div class="question-answer upload-area">
                    <el-upload
                      action="#"
                      :auto-upload="false"
                      :on-change="(file) => handleFileChange(file, question.id)"
                      :show-file-list="false"
                    >
                      <el-button type="primary" size="small">上传答案文件</el-button>
                    </el-upload>
                    <div v-if="answers[question.id]" class="file-name">
                      {{ answers[question.id] }}
                    </div>
                  </div>
                </template>
                <template v-else>
                  <!-- 主观题作答区域 -->
                  <div class="question-answer">
                    <WangEditor
                      :ref="'editor_' + question.id"
                      :key="'editor_' + question.id"
                      v-model="answers[question.id]"
                      :mode="'default'"
                      @change="(html) => handleEditorChange(question.id, html)"
                    />
                  </div>
                </template>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 考试操作栏 -->
      <div class="exam-footer">
        <div class="question-nav">
          <el-button
            v-for="type in questionTypes"
            :key="type.id"
            :type="activeTab === type.id.toString() ? 'primary' : ''"
            size="mini"
            @click="activeTab = type.id.toString()"
          >
            {{ type.name }}({{ type.count }})
          </el-button>
        </div>
        <div class="exam-actions">
          <el-button @click="handleSaveDraft">保存草稿</el-button>
          <el-button type="primary" @click="handleSubmit">提交试卷</el-button>
        </div>
      </div>

      <!-- 提交确认对话框 -->
      <el-dialog
        title="提交确认"
        :visible.sync="submitDialogVisible"
        width="500px"
        :close-on-click-modal="false"
        :show-close="false"
      >
        <div class="submit-confirm">
          <p>您确定要提交试卷吗？提交后将无法修改答案。</p>
          <div class="answered-count">
            已完成: {{ answeredCount }} / {{ totalQuestions }} 题
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="submitDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSubmit">确定提交</el-button>
        </div>
      </el-dialog>

      <!-- 全屏提示 -->
      <el-dialog
        title="全屏提示"
        :visible.sync="fullscreenDialogVisible"
        width="500px"
        :close-on-click-modal="false"
        :show-close="false"
      >
        <div class="fullscreen-tip">
          <i class="el-icon-full-screen"></i>
          <p>考试需要全屏模式下进行，请允许全屏模式</p>
          <p>考试期间不允许切换窗口或标签页</p>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="enterFullscreen">进入全屏</el-button>
        </div>
      </el-dialog>
    </div>
  </fullscreen-container>
</template>

<script>
import { getExamDetail, submitExam, saveExamDraft } from '@/api/exam/sudentGroupDetail'
import _ from 'lodash'
import WangEditor from '@/components/WangEditor'
import { listQuestionTypes } from '@/api/question2/type'
import FullscreenContainer from './FullscreenContainer'
import FormulaRenderer from "@/components/FormulaRenderer/index.vue";

export default {
  name: 'ExamActivity',
  components: {
    FormulaRenderer,
    WangEditor,
    FullscreenContainer
  },
  data() {
    return {
      activityMonitor: {
        mouseIdleTime: 0,
        keyboardIdleTime: 0,
        maxIdleTime: 120000, // 2分钟无操作视为异常
        checkInterval: 10000 // 10秒检查一次
      },
      activityInterval: null,
      screenshotInterval: null,
      screenshotIntervalTime: 30000, // 30秒截图一次
      groupId: null,
      examId: null,
      examType: 1, // 1-考试 2-测评 3-作业
      examInfo: {
        title: '',
        totalScore: 0,
        passScore: null,
        timeLimit: 0
      },
      allQuestionTypes: [], // 所有题型配置
      questionTypes: [], // 当前考试包含的题型分组
      questions: [],
      answers: {},
      activeTab: '1', // 默认选中第一个题型
      timerVisible: true,
      countdown: 0,
      timer: null,
      submitDialogVisible: false,
      fullscreenDialogVisible: false,
      isSubmitting: false,
      fullscreenEnabled: false
    }
  },
  computed: {
    answeredCount() {
      return Object.keys(this.answers).filter(key => {
        const answer = this.answers[key]
        return answer !== null && answer !== undefined && answer !== '' &&
          (!Array.isArray(answer) || answer.length > 0)
      }).length
    },
    totalQuestions() {
      return this.questions.length
    }
  },
  created() {
    console.log('this.$route.query.id',this.$route.query.id);
    console.log('this.$route.query.groupId',this.$route.query.groupId);
    this.examId = this.$route.query.id
    this.examType = parseInt(this.$route.query.type) || 1
    this.groupId = this.$route.query.groupId
    this.loadExamData()
  },
  mounted() {
    // 监听全屏退出事件
    this.$refs.fullscreenContainer.$on('fullscreen-exited', this.handleFullscreenExit)
    if (this.antiCheating) {
      this.startActivityMonitoring()
    }

    if (this.antiCheating) {
      this.startScreenshotInterval()
    }


  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
    // 在beforeDestroy中添加
    this.stopScreenshotInterval()
    this.stopActivityMonitoring()
    // 移除事件监听
    this.$refs.fullscreenContainer.$off('fullscreen-exited', this.handleFullscreenExit)
  },
  methods: {
    // 处理全屏退出事件
    handleFullscreenExit() {
      // 关闭当前标签页
      this.$store.dispatch("tagsView/delView", this.$route)

      // 返回上一页
      this.$router.go(-1)

      // 可选：显示提示信息
      this.$message.warning('您已退出考试全屏模式')
    },

    startActivityMonitoring() {
      if (!this.antiCheating) return

      this.stopActivityMonitoring()

      // 重置活动时间
      this.resetActivityTimers()

      // 添加事件监听
      window.addEventListener('mousemove', this.resetMouseActivity)
      window.addEventListener('keydown', this.resetKeyboardActivity)

      // 启动定时检查
      this.activityInterval = setInterval(() => {
        this.checkActivity()
      }, this.activityMonitor.checkInterval)
    },

    stopActivityMonitoring() {
      if (this.activityInterval) {
        clearInterval(this.activityInterval)
        this.activityInterval = null
      }

      // 移除事件监听
      window.removeEventListener('mousemove', this.resetMouseActivity)
      window.removeEventListener('keydown', this.resetKeyboardActivity)
    },

    resetMouseActivity() {
      this.activityMonitor.mouseIdleTime = 0
    },

    resetKeyboardActivity() {
      this.activityMonitor.keyboardIdleTime = 0
    },

    resetActivityTimers() {
      this.activityMonitor.mouseIdleTime = 0
      this.activityMonitor.keyboardIdleTime = 0
    },

    checkActivity() {
      this.activityMonitor.mouseIdleTime += this.activityMonitor.checkInterval
      this.activityMonitor.keyboardIdleTime += this.activityMonitor.checkInterval

      if (this.activityMonitor.mouseIdleTime >= this.activityMonitor.maxIdleTime ||
        this.activityMonitor.keyboardIdleTime >= this.activityMonitor.maxIdleTime) {
        this.recordMonitoringEvent('inactivity-detected')
        this.$message.warning('检测到长时间无操作，请保持考试状态')
      }
    },

    // 处理防作弊检测
    handleCheating(event) {
      // 记录监考事件
      this.recordMonitoringEvent(event.type)

      if (event.type === 'exit-fullscreen') {
        this.handleFullscreenExit()
      } else if (event.type === 'exceed-switch-limit') {
        this.$message.error('检测到多次切换页面，已自动提交试卷')
        this.confirmSubmit()
      }
    },
    startScreenshotInterval() {
      if (!this.antiCheating) return

      this.stopScreenshotInterval()

      this.screenshotInterval = setInterval(() => {
        this.takeScreenshot()
      }, this.screenshotIntervalTime)
    },

    stopScreenshotInterval() {
      if (this.screenshotInterval) {
        clearInterval(this.screenshotInterval)
        this.screenshotInterval = null
      }
    },

    async takeScreenshot() {
      try {
        const canvas = await html2canvas(document.body, {
          logging: false,
          useCORS: true,
          allowTaint: true,
          scale: 0.5 // 降低分辨率以减少数据量
        })

        const screenshot = canvas.toDataURL('image/jpeg', 0.7)
        this.recordMonitoringEvent('periodic-screenshot', screenshot)
      } catch (error) {
        console.error('截图失败:', error)
      }
    },

    async loadExamData() {
      console.log('加载考试数据');
      try {
        // 并行获取考试详情和题型列表
        const [examRes, typesRes] = await Promise.all([
          getExamDetail(this.examId),
          listQuestionTypes()
        ])
        console.log('A');


        const data = examRes.data
        this.allQuestionTypes = typesRes.data

        this.examInfo = {
          title: data.title,
          totalScore: data.totalScore,
          passScore: data.passScore,
          timeLimit: data.timeLimit
        }

        // 处理题目数据
        this.processQuestions(data.questions)

        // 设置默认激活的题型标签
        if (this.questionTypes.length > 0) {
          this.activeTab = this.questionTypes[0].id.toString()
        }
        console.log('B');


        // 初始化答案
        console.log('data.answers',data.answers)
        if (data.answers) {
          try {
            const parsedAnswers = typeof data.answers === 'string' ? JSON.parse(data.answers) : data.answers
            const savedAnswers = typeof parsedAnswers.answers === 'string' ? JSON.parse(parsedAnswers.answers) : parsedAnswers.answers

            // 先设置answers数据
            console.log('第一次尝试设置answer',savedAnswers)
            this.answers = this.processSavedAnswers(savedAnswers)


            // 然后单独设置编辑器内容
            console.log('第二次尝试设置answer', savedAnswers)
            this.setEditorContents(savedAnswers)
          } catch (e) {
            console.error('解析答案失败:', e)
            this.answers = {}
          }
        } else {
          this.answers = {}
        }
        console.log('C');

        // 初始化倒计时
        if (this.examInfo.timeLimit) {
          this.countdown = this.examInfo.timeLimit * 60
          this.startTimer()
        }

        // 检查全屏支持
        this.checkFullscreenSupport()
      } catch (error) {
        this.$message.error('获取考试信息失败: ' + error.message)
      }
    },

    processSavedAnswers(savedAnswers) {
      const processed = {}
      for (const [questionId, answer] of Object.entries(savedAnswers)) {
        const question = this.questions.find(q => q.id.toString() === questionId.toString())
        if (question && !this.isChoiceType(question.type)) {
          // 非选择题，可能是富文本答案
          processed[questionId] = this.ensureHtmlFormat(answer)
        } else {
          processed[questionId] = answer
        }
      }

      // 在下一个事件循环中设置编辑器内容
      this.$nextTick(() => {
        this.setEditorContents(processed)
      })

      return processed
    },

    setEditorContents(answers) {
      this.$nextTick(async () => {
        for (const question of this.questions) {
          if (!this.isChoiceType(question.type)) {
            const editorRef = this.$refs[`editor_${question.id}`]
            if (editorRef && editorRef[0] && answers[question.id]) {
              try {
                // 等待编辑器准备好
                if (!editorRef[0].isReady) {
                  await new Promise(resolve => {
                    editorRef[0].$once('ready', resolve)
                  })
                }
                // 设置内容
                await editorRef[0].setContent(answers[question.id])
              } catch (error) {
                console.error(`设置题目 ${question.id} 内容失败:`, error)
              }
            }
          }
        }
      })
    },

    ensureHtmlFormat(content) {
      if (!content) return ''
      if (typeof content === 'string' && (!content.startsWith('<') || !content.endsWith('>'))) {
        return `<p>${content}</p>`
      }
      return content
    },

    processQuestions(questions) {
      // 处理题目数据，添加题型名称等信息
      this.questions = questions.map(q => {
        const type = this.getTypeInfo(q.type)
        return {
          ...q,
          typeName: type.name || '未知题型',
          typeCode: type.code || ''
        }
      })

      // 分组题型数据
      this.questionTypes = this.groupQuestionsByType()
    },

    groupQuestionsByType() {
      const typeMap = {}

      this.questions.forEach(q => {
        if (!typeMap[q.type]) {
          const typeInfo = this.getTypeInfo(q.type)
          typeMap[q.type] = {
            id: q.type,
            name: typeInfo.name || '未知题型',
            code: typeInfo.code || '',
            count: 0,
            score: 0
          }
        }
        typeMap[q.type].count++
        typeMap[q.type].score += q.score
      })

      return Object.values(typeMap).sort((a, b) => a.id - b.id)
    },

    getQuestionsByType(typeId) {
      return this.questions.filter(q => q.type === typeId)
    },

    getTypeInfo(typeId) {
      return this.allQuestionTypes.find(t => t.id === typeId) || {}
    },

    isChoiceType(typeId) {
      const type = this.getTypeInfo(typeId)
      return type.hasOption === 1 || type.hasOption === 2
    },

    isMultiChoiceType(typeId) {
      const type = this.getTypeInfo(typeId)
      return type.hasOption === 2
    },

    isAnswered(questionId) {
      const answer = this.answers[questionId]
      return answer !== null && answer !== undefined && answer !== '' &&
        (!Array.isArray(answer) || answer.length > 0)
    },

    isOptionSelected(questionId, optionId) {
      if (!this.answers[questionId]) return false

      if (Array.isArray(this.answers[questionId])) {
        return this.answers[questionId].includes(optionId)
      } else {
        return this.answers[questionId] === optionId
      }
    },

    handleSelectOption(questionId, optionId) {
      const question = this.questions.find(q => q.id === questionId)
      if (!question) return

      const typeInfo = this.getTypeInfo(question.type)
      if (!typeInfo) return

      // 根据题型配置处理答案
      if (typeInfo.hasOption === 1) {
        // 单选题 - 直接替换答案
        this.$set(this.answers, questionId, optionId)
      } else if (typeInfo.hasOption === 2) {
        // 多选题 - 切换选项
        if (!this.answers[questionId]) {
          this.$set(this.answers, questionId, [])
        }

        const index = this.answers[questionId].indexOf(optionId)
        if (index === -1) {
          this.answers[questionId].push(optionId)
        } else {
          this.answers[questionId].splice(index, 1)
        }
      }

      this.saveDraftDebounced()
    },

    handleEditorChange(questionId, html) {
      this.$set(this.answers, questionId, html)
      this.saveDraftDebounced()
    },

    handleFileChange(file, questionId) {
      this.$set(this.answers, questionId, file.name)
      this.saveDraftDebounced()
    },

    saveDraftDebounced: _.debounce(function() {
      this.handleSaveDraft()
    }, 1000),

    handleSaveDraft() {
      saveExamDraft(this.examId, JSON.stringify(this.answers)).then(() => {
        // 草稿保存成功
      }).catch(error => {
        this.$message.error('保存草稿失败: ' + error.message)
      })
    },

    handleSubmit() {
      this.submitDialogVisible = true
    },

    confirmSubmit() {
      if (this.isSubmitting) return

      this.isSubmitting = true
      this.submitDialogVisible = false

      submitExam(this.examId, JSON.stringify(this.answers)).then(() => {
        this.$message.success('试卷提交成功')
        // 提交后允许退出全屏
        this.$nextTick(() => {
          // 关闭当前tabs
          this.$store.dispatch("tagsView/delView", this.$route);
          this.$router.go(-1) // 返回上一页
        })
      }).catch(error => {
        // 关闭当前tabs
        this.$store.dispatch("tagsView/delView", this.$route);
        this.$router.go(-1) // 返回上一页
        this.$message.error('提交失败: ' + '您之前提交过试卷，请勿重复提交')
      }).finally(() => {
        this.isSubmitting = false
      })
    },

    startTimer() {
      if (this.timer) {
        clearInterval(this.timer)
      }

      this.timer = setInterval(() => {
        this.countdown--

        if (this.countdown <= 0) {
          clearInterval(this.timer)
          this.$message.warning('考试时间已结束，将自动提交试卷')
          this.confirmSubmit()
        } else if (this.countdown <= 300) {
          // 最后5分钟提示
          if (this.countdown % 60 === 0) {
            this.$notify.warning({
              title: '时间提醒',
              message: `距离考试结束还有 ${this.countdown / 60} 分钟`,
              duration: 5000
            })
          }
        }
      }, 1000)
    },

    formatTime(seconds) {
      const h = Math.floor(seconds / 3600)
      const m = Math.floor((seconds % 3600) / 60)
      const s = seconds % 60

      return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
    },

    checkFullscreenSupport() {
      this.fullscreenEnabled = !!(
        document.fullscreenEnabled ||
        document.webkitFullscreenEnabled ||
        document.msFullscreenEnabled
      )

      if (!this.fullscreenEnabled) {
        this.$message.warning('您的浏览器不支持全屏模式，考试体验可能受影响')
      } else {
        this.fullscreenDialogVisible = true
      }
    },

    enterFullscreen() {
      this.fullscreenDialogVisible = false
      // 由FullscreenContainer组件处理全屏逻辑
    }
  }
}
</script>

<style scoped>
.exam-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #fff;
  padding: 20px;
  box-sizing: border-box;
}

.exam-header {
  padding: 15px 20px;
  background: #f5f7fa;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 20px;
}

.exam-title h2 {
  margin: 0 0 5px 0;
  font-size: 18px;
}

.exam-meta {
  display: flex;
  gap: 15px;
  color: #606266;
  font-size: 14px;
}

.exam-timer {
  font-size: 16px;
  display: flex;
  align-items: center;
}

.exam-timer i {
  margin-right: 5px;
}

.time-count {
  font-weight: bold;
  color: #f56c6c;
}

.exam-content {
  flex: 1;
  overflow: auto;
  padding: 0 10px;
}

.question-list {
  padding: 10px 0;
}

.question-item {
  margin-bottom: 30px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  transition: all 0.3s;
}

.question-item.answered {
  border-left: 3px solid #67c23a;
}

.question-item.choice-type {
  border-left-color: #409EFF;
}

.question-item.upload-type {
  border-left-color: #E6A23C;
}

.question-item.text-type {
  border-left-color: #67C23A;
}

.question-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.question-index {
  font-weight: bold;
}

.question-type {
  color: #909399;
  font-size: 14px;
}

.question-content {
  margin-bottom: 15px;
  line-height: 1.6;
}

.question-options {
  margin: 15px 0;
}

.option-item {
  padding: 10px;
  margin-bottom: 8px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.option-item:hover {
  background: #f5f7fa;
}

.option-item.selected {
  background: #ecf5ff;
  border-color: #c6e2ff;
}

.option-item.multi-selected {
  background: #f0f9eb;
  border-color: #e1f3d8;
}

.option-code {
  font-weight: bold;
  margin-right: 10px;
}

.question-answer {
  margin-top: 15px;
}

.upload-area {
  margin-top: 15px;
}

.file-name {
  margin-top: 10px;
  color: #409eff;
}

.exam-footer {
  padding: 15px 20px;
  background: #f5f7fa;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.question-nav {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.exam-actions {
  display: flex;
  gap: 15px;
}

/* 提交确认对话框样式 */
.submit-confirm {
  text-align: center;
}

.answered-count {
  margin-top: 20px;
  font-size: 16px;
  color: #409eff;
}

/* 全屏提示样式 */
.fullscreen-tip {
  text-align: center;
}

.fullscreen-tip i {
  font-size: 50px;
  color: #409eff;
  margin-bottom: 15px;
}

.fullscreen-tip p {
  margin: 10px 0;
}

/* WangEditor 样式调整 */
.w-e-text-container {
  z-index: auto !important;
}
</style>
